package com.bootdo.clouddo.controller.juejin;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bootdo.clouddo.domain.juejin.PostDO;
import com.bootdo.clouddo.service.juejin.IPostDetailService;
import com.bootdo.clouddo.service.juejin.IPostService;
import com.bootdo.clouddo.utils.xf.FileUtil;
import com.bootdo.clouddo.utils.xf.HttpUtil;
import com.bootdo.clouddo.utils.xf.ReduceHtml2Text;
import com.bootdo.clouddo.utils.R;
import com.bootdo.clouddo.utils.StringUtils;



@RestController
@RequestMapping("/juejin/reading")
public class ReadingController {
	
    @Value("${xunfei.appid}")
    private String appid;

    @Value("${xunfei.apikey}")
    private String apikey;
    
 // 合成webapi接口地址
 	private static final String WEBTTS_URL = "http://api.xfyun.cn/v1/service/v1/tts";
 	// 应用ID
 	private static final String APPID = "5c865c16";
 	// 接口密钥
 	private static final String API_KEY = "0aa8c7fb21d90cf084b86d2b395480e0";
 	// 待合成文本
 	private static final String TEXT = "测试音频";
 	// 音频编码
 	private static final String AUE = "raw";
 	// 采样率
 	private static final String AUF = "audio/L16;rate=16000";
 	// 语速
 	private static final String SPEED = "50";
 	// 音量
 	private static final String VOLUME = "50";
 	// 音调
 	private static final String PITCH = "50";
 	// 发音人
 	private static final String VOICE_NAME = "xiaoyan";
 	// 引擎类型
 	private static final String ENGINE_TYPE = "intp65";
 	// 文本类型
 	private static final String TEXT_TYPE = "text";
 	
	@Autowired
	private IPostService postService;
	
	@Autowired
	private IPostDetailService detailService;
 	
 	@RequestMapping
 	public R getReading(String postId) throws UnsupportedEncodingException {
 		String text = null;
 		PostDO post = postService.get(postId);
		if(post == null)
			return R.error("post_not_found");
		post.setDetail(detailService.get(postId));
		
		text = ReduceHtml2Text.removeHtmlTag(post.getDetail().getContent());
		
 		Map<String, String> header = buildHttpHeader();
		LinkedList list = new LinkedList();
		for (int i = 0; i < text.length() /50; i++) {
			String str = text.substring(50*i, 50*(i+1));
			if(StringUtils.isNotBlank(str)) {
				String path = download(str, header);
				list.add(path);
			}
		}
		return R.data(list);
		
 	}
 	
 	public String download(String text, Map<String, String> header) throws UnsupportedEncodingException {
 		Map<String, Object> resultMap = HttpUtil.doPost2(WEBTTS_URL, header, "text=" + URLEncoder.encode(text, "utf-8"));
		System.out.println("占用内存大小： "+ URLEncoder.encode(text, "utf-8").getBytes().length);
		if (resultMap != null && "audio/mpeg".equals(resultMap.get("Content-Type"))) { // 合成成功
			if ("raw".equals(AUE)) {
				com.bootdo.clouddo.utils.xf.FileUtil.save("resource\\", resultMap.get("sid") + ".wav", (byte[]) resultMap.get("body"));
				System.out.println("合成 WebAPI 调用成功，音频保存位置：resource\\" + resultMap.get("sid") + ".wav");
			} else {
				FileUtil.save("resource\\", resultMap.get("sid") + ".mp3", (byte[]) resultMap.get("body"));
				System.out.println("合成 WebAPI 调用成功，音频保存位置：resource\\" + resultMap.get("sid") + ".mp3");
			}
			return resultMap.get("sid") + ".mp3";
		} else { // 合成失败
			System.out.println("合成 WebAPI 调用失败，错误信息：" + resultMap.get("body").toString());
			return null;
		}
 	}
 	
 	/**
	 * 合成 WebAPI 调用示例程序
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		
		Map<String, String> header = buildHttpHeader();
		
		Map<String, Object> resultMap = HttpUtil.doPost2(WEBTTS_URL, header, "text=" + URLEncoder.encode(TEXT, "utf-8"));
		System.out.println("占用内存大小： "+ URLEncoder.encode(TEXT, "utf-8").getBytes().length);
		if (resultMap != null && "audio/mpeg".equals(resultMap.get("Content-Type"))) { // 合成成功
			if ("raw".equals(AUE)) {
				com.bootdo.clouddo.utils.xf.FileUtil.save("resource\\", resultMap.get("sid") + ".wav", (byte[]) resultMap.get("body"));
				System.out.println("合成 WebAPI 调用成功，音频保存位置：resource\\" + resultMap.get("sid") + ".wav");
			} else {
				FileUtil.save("resource\\", resultMap.get("sid") + ".mp3", (byte[]) resultMap.get("body"));
				System.out.println("合成 WebAPI 调用成功，音频保存位置：resource\\" + resultMap.get("sid") + ".mp3");
			}
		} else { // 合成失败
			System.out.println("合成 WebAPI 调用失败，错误信息：" + resultMap.get("body").toString());
		}
	}

	/**
	 * 组装http请求头
	 */
	private static Map<String, String> buildHttpHeader() throws UnsupportedEncodingException {
		String curTime = System.currentTimeMillis() / 1000L + "";
		String param = "{\"auf\":\"" + AUF + "\",\"aue\":\"" + AUE + "\",\"voice_name\":\"" + VOICE_NAME + "\",\"speed\":\"" + SPEED + "\",\"volume\":\"" + VOLUME + "\",\"pitch\":\"" + PITCH + "\",\"engine_type\":\"" + ENGINE_TYPE + "\",\"text_type\":\"" + TEXT_TYPE + "\"}";
		String paramBase64 = new String(Base64.encodeBase64(param.getBytes("UTF-8")));
		String checkSum = DigestUtils.md5Hex(API_KEY + curTime + paramBase64);
		Map<String, String> header = new HashMap<String, String>();
		header.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
		header.put("X-Param", paramBase64);
		header.put("X-CurTime", curTime);
		header.put("X-CheckSum", checkSum);
		header.put("X-Appid", APPID);
		return header;
	}

}
